﻿
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WeiXinPF.Common;
using VTemplate.Engine;
using WeiXinPF.Model;


namespace WeiXinPF.Templates
{
    public class TravelTemplate
    {
        WeiXinPF.DAL.templatesDal tDal = new DAL.templatesDal();


        #region 属性
        protected internal string ccRight = "(c)2014";
        /// <summary>
        /// 当前页面的模板文档对象
        /// </summary>
        protected TemplateDocument Document
        {
            get;
            private set;
        }

        /// <summary>
        /// 当前页面的模板文档的配置参数
        /// </summary>
        protected virtual TemplateDocumentConfig DocumentConfig
        {
            get
            {
                return TemplateDocumentConfig.Default;
            }
        }

        /// <summary>
        /// 编号id
        /// </summary>
        public int detailid { get; set; }

        /// <summary>
        /// 微帐号
        /// </summary>
        public int wid { get; set; }
        /// <summary>
        /// 微信用户openid
        /// </summary>
        public string openid { get; set; }

        /// <summary>
        /// 模版类型
        /// </summary>
        public TemplateType tType { get; set; }

        /// <summary>
        /// 模版文件名称
        /// </summary>
        public string templateFileName { get; set; }

        /// <summary>
        /// 模版文件的文件夹名称
        /// </summary>
        public string templateDictoryName { get; set; }

        /// <summary>
        /// 模版的物理路径（全完）
        /// </summary>
        public string serverPath { get; set; }

        /// <summary>
        /// 模版的虚拟路径，比如/shop/templates/default
        /// </summary>
        public string tPath { get; set; }

        public int categoryid
        {
            get; set;
        }
        #endregion

        #region 构造函数

        /// <summary>
        /// 模版初始化
        /// </summary>
        /// <param name="tPath">模版文件的虚拟路径</param>
        /// <param name="serverPath">模版文件的完全路径</param>
        /// <param name="wid"></param>
        public TravelTemplate(string tPath, string serverPath, int wid,int categoryid)
        {

            this.serverPath = serverPath;
            this.tPath = tPath;
            this.Document = new TemplateDocument(serverPath, Encoding.UTF8, this.DocumentConfig);
            this.wid = wid;
            this.categoryid = categoryid;
            this.detailid = detailid;
        }

        /// <summary>
        /// 模版初始化
        /// </summary>
        /// <param name="templateDictoryName">模版文件的文件夹名称</param>
        /// <param name="tPath">模版文件的虚拟路径</param>
        /// <param name="serverPath">模版文件的完全路径</param>
        /// <param name="wid"></param>
        public TravelTemplate(string templateDictoryName, string tPath, string serverPath, int wid,int categoryid)
        {

            this.templateDictoryName = templateDictoryName;
            this.serverPath = serverPath;
            this.tPath = tPath;
            this.Document = new TemplateDocument(serverPath, Encoding.UTF8, this.DocumentConfig);
            this.wid = wid;
            this.detailid = detailid;
            this.categoryid = categoryid;
        }


        /// <summary>
        /// 模版初始化
        /// </summary>
        /// <param name="templateFileName">模版文件的名称</param>
        /// <param name="templateDictoryName">模版文件的文件夹名称</param>
        /// <param name="tPath">模版文件的虚拟路径</param>
        /// <param name="serverPath">模版文件的完全路径</param>
        /// <param name="wid"></param>
        public TravelTemplate(string templateFileName, string templateDictoryName, string tPath, string serverPath, int wid,int categoryid)
        {
            this.templateFileName = templateFileName;
            this.templateDictoryName = templateDictoryName;
            this.serverPath = serverPath;
            this.tPath = tPath;
            this.Document = new TemplateDocument(serverPath, Encoding.UTF8, this.DocumentConfig);
            this.wid = wid;
            this.detailid = detailid;
            this.categoryid = categoryid;


        }

        #endregion


        /// <summary>
        /// 输出最终的html
        /// </summary>
        /// <param name="templateFileName"></param>
        /// <param name="tPath"></param>
        /// <param name="wid"></param>
        public void OutPutHtml(string templateFileName, int wid)
        {
            //注册一个自定义函数
            //this.Document.RegisterGlobalFunction(this.ComputeMoney);

            //对VT模板里的config变量赋值 
            Model.wxcodeconfig wxconfig = tDal.GetModelByWid(wid, "/templates/index/" + templateFileName);
            if (wxconfig.wxstatus == 0)
            {
                HttpContext.Current.Response.Write("帐号已过期！请及时充值！");
            }
            this.Document.Variables.SetValue("config", wxconfig);

            //BLL.wx_shop_setting setBll = new BLL.wx_shop_setting();

            BLL.wx_travel_marker setBll = new BLL.wx_travel_marker();

            //if (!setBll.ExistsWid(wid))
            //{
            //    HttpContext.Current.Response.Write("请先选择模版！");
            //    HttpContext.Current.Response.End();
            //}
            //Model.wx_shop_setting setting = setBll.GetModelList("wid=" + wid)[0];

            Model.wx_travel_setting setting = new BLL.wx_travel_setting().GetModel(wid);

            this.Document.Variables.SetValue("travelconfig", setting);

            this.Document.SetValue("wid", wid);
            this.Document.SetValue("ccright", ccRight);
            this.Document.SetValue("yuming", MyCommFun.getWebSite());
            this.Document.SetValue("thisurl", MyCommFun.getTotalUrl());
            this.Document.SetValue("indexurl", indexUrl());
            //this.Document.SetValue("categoryurl", MyCommFun.urlAddOpenid("/shop/category.aspx?wid=" + wid, openid));
            //this.Document.SetValue("carturl", MyCommFun.urlAddOpenid("/shop/cart.aspx?wid=" + wid, openid));//upd
            this.Document.SetValue("userurl", "/pano360/index.aspx?wid=" + wid);
            this.Document.SetValue("openid", openid);
            this.Document.Variables.SetValue("this", this);
            if (tType == TemplateType.Index)
            {
                // ProductClassPage();
            }
            else if (tType == TemplateType.News)
            {
                SetDetailPage();
            }
            else if (tType == TemplateType.Cart)
            {
                // CartDetailPage();
            }
            else if (tType == TemplateType.confirmOrder)
            {
                //  confirmOrder();
            }
            else if (tType == TemplateType.editaddr)
            {
                //  editAddrPage();
            }
            else if (tType == TemplateType.orderSuccess)
            {
                //  OrderSuccessPage();
            }
            else if (tType == TemplateType.userinfo)
            {
                // userinfoPage();
            }
            else if (tType == TemplateType.orderDetail)
            {  //订单详情页面
               // orderDetail();
            }

            //输出最终呈现的数据 
            this.Document.Render(HttpContext.Current.Response.Output);

        }

        #region 方法集合：注册到模版或者供模版调用


        /// <summary>
        /// 获得幻灯片列表二：优点：（1）使用function标签与foreach结合，可以从模版页面控制记录数量；（2）不需要实现注册到模版里
        /// </summary>
        /// <returns></returns>
        public IList<Model.wx_travel_picture> getHdp()
        {
            Tag tag = this.Document.CurrentRenderingTag;
            var attribute = tag.Attributes["rows"];

            IList<Model.wx_travel_picture> artlist = new List<Model.wx_travel_picture>();

            int rows = -1;//若为-1，则不做限制条件
            if (attribute != null && MyCommFun.isNumber(attribute.Value.GetValue()))
            {
                rows = MyCommFun.Obj2Int(attribute.Value.GetValue());
            }
            WeiXinPF.DAL.wx_travel_picture sibDal = new DAL.wx_travel_picture();
            artlist = sibDal.GetHDPByWid(this.detailid, rows);
            //detailid为0时为首页
            if (artlist != null && artlist.Count > 0)
            {
                Model.wx_travel_picture cat = new Model.wx_travel_picture();
                for (int i = 0; i < artlist.Count; i++)
                {
                    cat = artlist[i];

                    if (cat.PicPath == null || cat.PicPath.Trim() == "")
                    {  //如果link_url为空，则直接调用本系统的信息
                        cat.PicPath = "javascript:;";

                    }
                    else
                    {
                        cat.PicPath = MyCommFun.urlAddOpenid(cat.PicPath, openid);
                    }
                }
            }
            return artlist;
        }

        /// <summary>
        /// 获得幻灯片列表二：优点：
        /// （1）使用function标签与foreach结合，可以从模版页面控制记录数量；
        /// （2）不需要实现注册到模版里
        /// </summary>
        /// <returns></returns>
        public IList<Model.wx_shop_indexbanner> getIndexHdp()
        {
            Tag tag = this.Document.CurrentRenderingTag;

            var attribute = tag.Attributes["rows"];
            IList<Model.wx_shop_indexbanner> artlist = new List<Model.wx_shop_indexbanner>();

            int rows = -1;//若为-1，则不做限制条件
            if (attribute != null && MyCommFun.isNumber(attribute.Value.GetValue()))
            {
                rows = MyCommFun.Obj2Int(attribute.Value.GetValue());
            }
            WeiXinPF.DAL.wx_shop_indexbanner sibDal = new DAL.wx_shop_indexbanner();
            artlist = sibDal.GetHDPByWid(wid, rows);

            if (artlist != null && artlist.Count > 0)
            {
                Model.wx_shop_indexbanner cat = new Model.wx_shop_indexbanner();
                for (int i = 0; i < artlist.Count; i++)
                {
                    cat = artlist[i];

                    if (cat.bannerLinkUrl == null || cat.bannerLinkUrl.Trim() == "")
                    {  //如果link_url为空，则直接调用本系统的信息
                        cat.bannerLinkUrl = "javascript:;";

                    }
                    else
                    {
                        string nPath = tPath.Substring(0,tPath.IndexOf("/templates"));
                        cat.bannerLinkUrl = "/" + nPath + "/detail.aspx?wid=" +wid.ToString() +"&detailid="+cat.id.ToString();
                        cat.bannerLinkUrl = MyCommFun.urlAddOpenid(cat.bannerLinkUrl, openid);
                    }
                }
            }
            return artlist;
        }

        /// <summary>
        /// 初始化index页面
        /// </summary>
        /// <returns></returns>
       



        /// <summary>
        /// 初始化detail页面
        /// </summary>
        /// <returns></returns>
        public void SetDetailPage()
        {
            Model.wx_travel_marker setting = new BLL.wx_travel_marker().GetModel(detailid);
            this.Document.Variables.SetValue("markerconfig", setting);
        }

        /// <summary>
        /// 获得存在的360度全景图
        /// </summary>
        /// <returns></returns>
        public IList<Model.wx_pano_jd> getPanos()
        {
            Tag tag = this.Document.CurrentRenderingTag;
            var attribute = tag.Attributes["rows"];

            IList<Model.wx_pano_jd> artlist = new List<Model.wx_pano_jd>();
            int rows = -1;//若为-1，则不做限制条件
            if (attribute != null && MyCommFun.isNumber(attribute.Value.GetValue()))
            {
                rows = MyCommFun.Obj2Int(attribute.Value.GetValue());
            }

            WeiXinPF.DAL.wx_pano_jd _Dal = new DAL.wx_pano_jd();

            string strwhere = " wid =  '" + wid.ToString() + "'";
            DataSet ds = _Dal.GetList(strwhere);
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                artlist.Add(_Dal.DataRowToModel(dr));
            }
            return artlist;
        }

        public IList<Model.advertisement> getAdvertisement()
        {
            Tag tag = this.Document.CurrentRenderingTag;
            var attribute = tag.Attributes["rows"];

            IList<Model.advertisement> advertisementlist = new List<Model.advertisement>();
            int rows = -1;//若为-1，则不做限制条件
            if (attribute != null && MyCommFun.isNumber(attribute.Value.GetValue()))
            {
                rows = MyCommFun.Obj2Int(attribute.Value.GetValue());
            }
            WeiXinPF.DAL.advertisement sibDal = new DAL.advertisement();

            string timenow = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string strwhere = " wid =  '" + wid.ToString() + "'  and categoryid =" + categoryid.ToString() + " and isdelete=0 and begintime < '" + timenow + "' and endtime > '" + timenow + "'";
            advertisementlist = sibDal.GetModelList(strwhere,rows,false);

            return advertisementlist;
        }


        /// <summary>
        /// 商城首页的url
        /// </summary>
        /// <returns></returns>
        private string indexUrl()
        {
            string url = "";
            // url = MyCommFun.getWebSite() + "/shop/index.aspx?wid=" + wid;
            url = MyCommFun.urlAddOpenid("/pano360/index.aspx?wid=" + wid, openid);
            return url;
        }

        #endregion
    }
}
